package base

import (
	"gin-base/base/config"
	"net/http"
	"time"
)

func init() {

}

func RunGin(router http.Handler) {
	var (
		endRunning = make(chan bool, 1)
	)

	/**
	Config :
		http.enable = true
		http.port = 610
	*/
	if config.Cfg.Listen.EnableHTTP {
		go func() {
			time.Sleep(20 * time.Microsecond)
			s := &http.Server{
				Addr:         ":" + config.Cfg.Listen.HTTPPort,
				Handler:      router,
				ReadTimeout:  10 * time.Second,
				WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20,
			}

			if err := s.ListenAndServe(); err != nil {
				panic("start http server error:" + err.Error())

				time.Sleep(100 * time.Microsecond)
				endRunning <- true
			}
		}()
	}

	/**
	Config :
		https.enable = true
		https.port = 611
		https.certFile = "ssl-cert/ssl.crt"
		https.keyFile = "ssl-cert/ssl.key"
	*/
	if config.Cfg.Listen.EnableHTTPS {
		go func() {
			s := &http.Server{
				Addr:         ":" + config.Cfg.Listen.HTTPSPort,
				Handler:      router,
				ReadTimeout:  10 * time.Second,
				WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20,
			}

			if err := s.ListenAndServeTLS(config.Cfg.Listen.HTTPSCertFile, config.Cfg.Listen.HTTPSKeyFile); err != nil {
				panic("start https server error:" + err.Error())

				time.Sleep(100 * time.Microsecond)
				endRunning <- true
			}
		}()
	}

	<-endRunning
	return
}
